<template>
  <el-select
    v-model="selectValue"
    style="width: 100%"
    :placeholder="placeholder"
    :disabled="disabled"
    clearable
    filterable
    @change="handleChange"
  >
    <el-option
      v-for="(item, index) in options"
      :key="index"
      :label="item.deptName"
      :value="item.deptCode"
    ></el-option>
  </el-select>
</template>

<script setup name="DeptSelect">
import { getFactoryTree, depeIdSelectList } from "@/api/system/dept";
import { toRefs, ref, onMounted, computed, watch } from "vue";

const props = defineProps({
  disabled: {
    type: Boolean,
    default: false,
  },
  type: {
    type: String,
    default: "",
  },
  placeholder: {
    type: String,
    default: "",
  },
  parent: {
    type: [String, Number],
    default: "",
  },
});

const { type, disabled, parent } = toRefs(props);

const selectValue = defineModel();
const selectName = defineModel("name");
const options = ref([]);
const emit = defineEmits(["change"]);

const workshop = defineModel("workshop");
const line = defineModel("line");
const section = defineModel("section");
const storehouse = defineModel("storehouse");
const bin = defineModel("bin");

const deptName = {
  factory: "factory",
  workshop: "station",
  line: "line",
  section: "craft",
};

const isFactory = computed(() => {
  return type.value === "factory";
});

watch(
  () => parent.value,
  (val) => {
    if (val) {
      getList();
    } else {
      options.value = [];
    }
  }
);

function handleChange(val) {
  switch (type.value) {
    case "factory":
      workshop.value = "";
      line.value = "";
      section.value = "";
      break;
    case "workshop":
      line.value = "";
      section.value = "";
      break;
    case "line":
      section.value = "";
      break;
    case "section":
      storehouse.value = "";
      bin.value = "";
      break;
    case "storehouse":
      bin.value = "";
      break;
  }
  let selected = null;
  for (let i = 0; i < options.value.length; i++) {
    if (val === options.value[i].deptCode) {
      selected = options.value[i];
      break;
    }
  }

  selectName.value = selected?.deptName;
  emit("change", selected);
}

function getList() {
  if (isFactory.value) {
    getFactoryTree().then((res) => {
      options.value = res.data;
    });
  } else {
    depeIdSelectList({
      deptType: deptName[type.value],
      deptCode: parent.value,
    }).then((res) => {
      options.value = res.data;
    });
  }
}
onMounted(() => {
  if (parent.value || isFactory.value) {
    getList();
  }
});
// getList();
</script>
